<?php
	
	namespace App\Http\Controllers\Admin\ExportContract;
	
	use Illuminate\Http\Request;
	use App\Http\Controllers\Controller;
	use DB;
	use PhpOffice\PhpSpreadsheet\Cell\DataType;
	use PhpOffice\PhpSpreadsheet\IOFactory;
	use QrCode;
//	分发单
	class ExportContractFFController extends Controller
	{
		
		private function getvolclass($val)
		{
			if ($val->class === '/') {
				# 电压等级
				$voltage_class = "{$val->voltage}";
			}
			else if ($val->voltage === '/') {
				# 分类
				$voltage_class = "{$val->class}";
			}
			else {
				# 电压等级+分类
				$voltage_class = "{$val->voltage}/{$val->class}";
			}
			return $voltage_class;
		}
		
		public function export(Request $request)
		{
			// sleep (5);
			$contract_id = $request->id;
			$data_gaiyao = DB::table('a_contract_gaiyao')->where('contract_id', $contract_id)->orderBy('id', 'asc')->get();
			if ($data_gaiyao->isEmpty()) {
				return '内容为空';
			}
			$data_contract = DB::table('a_contract')->find($contract_id);
			// dd($data_contract);
			
			// dd(base_path());
			// dd(public_path());
			$template_file = './storage/ExcelTemplate/检验分发单.xls'; //考虑到兼容Linux，斜杠用“/”
			if (!file_exists($template_file)) {
				return '模板文件不存在';
			}
			$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file); //读取模板文件
			$worksheet = $spreadsheet->getSheet(0); //按索引获取表单，从 0 开始
            
			$sample_chuli = $data_contract->sample_chuli;//不合格样品处理
			$get_report = $data_contract->get_report;//取报告方式
            $worksheet->getCell('C7')->setValue($sample_chuli);                    //不合格样品处理
            $worksheet->getCell('G7')->setValue($get_report);                      //取报告方式
            $worksheet->getCell('K7')->setValue($data_contract->deadline);         //要求完成日期
			
			$setting = DB::table('setting')->find(1);
			
			$worksheet->getCell('A1')->setValue($setting->name_rep);                //报告名称
			$worksheet->getCell('L3')->setValue($data_contract->batchNum);          //合同编号

			$first_flag  = false; //第一次循环的标志
			$rowIndex    = 6;
			$totalCount  = 0;
			foreach ($data_gaiyao as $val) {
				if ($first_flag) {
					# code...
					$worksheet->insertNewRowBefore($rowIndex, 1);               //在第10行之前插入1个新行
					// $worksheet->getRowDimension('10')->setRowHeight(15);//设置行高
					// $worksheet->mergeCells('A18:E22');//合并单元格
					$worksheet->mergeCells('A' . $rowIndex . ':C' . $rowIndex);
					$worksheet->mergeCells('E' . $rowIndex . ':F' . $rowIndex);
					$worksheet->mergeCells('H' . $rowIndex . ':M' . $rowIndex);
					$worksheet->mergeCells('N' . $rowIndex . ':O' . $rowIndex);
				}

				$worksheet->setCellValue('A'.$rowIndex, $val->tool_name);          //样品名称
				$worksheet->setCellValue('D'.$rowIndex, $val->bar_codes);          //编号
				$worksheet->setCellValue('E'.$rowIndex, $this->getvolclass($val)); //电压等级/种类
				$worksheet->setCellValue('G'.$rowIndex, $val->count . $val->unit); //数量
				$worksheet->setCellValue('H'.$rowIndex, $val->item_names); //检验项目
				$worksheet->setCellValue('N'.$rowIndex, $val->std_num); //检验项目

				//设置行高
				$worksheet->getRowDimension($rowIndex)->setRowHeight(25);
				$strlen = strlen($val->item_names);
				if ($strlen > 120) {
					$height = floor($strlen / 66) * 20;  //按照每行66个文字计算,计算出行高
					$worksheet->getRowDimension($rowIndex)->setRowHeight($height);
				}
				// break;
				$first_flag = true;
				$rowIndex++;
				$totalCount += $val->count;
			}
			$worksheet->getCell('C' . ($rowIndex + 3))->setValue('共计：' . $totalCount . '件；其他备注：' . $data_contract->remark); //备注

			//----------直接在浏览器下载----start
			$file_name = "检验分发单" . $data_contract->batchNum . ".xls";                                                        //输出的文件名称
			// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
			header('Content-Type: application/vnd.ms-excel');                                                               //告诉浏览器输出Excel 03版本文件
			header('Content-Disposition: attachment;filename=' . urlencode($file_name));                                    //告诉浏览器输出的文件名称
			header('Cache-Control: max-age=0');                                                                             //禁止缓存
			//----------直接在浏览器下载----end
			
			
			$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
			$writer->setPreCalculateFormulas(false); //禁用公式预先计算
			// $writer->save('write.xls');//将Excel文件保存在服务器的磁盘上
			$writer->save('php://output');           //直接在浏览器下载
			
			/* //未测试通过
			// $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
			$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf');
			$writer->setPreCalculateFormulas(false);//禁用公式预先计算
			$writer->save("05featuredemo.pdf"); */
			
			//为了防止内存泄露，建议用完手动清理
			$spreadsheet->disconnectWorksheets();
			unset($spreadsheet);
		}
	}
